package eu.dicode.analysis.demonstrator;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * Reads dumped collocation analysis result and sends those results back in json format.
 */
@Controller
public class CollocationDataController {
  /**Where in the file system is our collocation data located.*/
  private final File collocationRawData;

  CollocationDataController(File collocationData) {
    this.collocationRawData = collocationData;
  }

  public CollocationDataController() throws IOException {
    InputStream stream = null;
    try {
      // we ship this file, if it is not there we want to fail with some sort of runtime error
      stream = this.getClass().getResourceAsStream("/dicode.analysis.demonstrator.properties");
      Properties props = new Properties();
      props.load(stream);

      this.collocationRawData = new File(props.getProperty(("eu.dicodeproject.analysis.collocation.location")));
    } finally {
      if (stream != null) stream.close();
    }
  }

  // TODO think about caching!
  @RequestMapping(value="/data/colloc/top.data", method = RequestMethod.GET)
  public void topValue(final Model model, final Writer responseWriter) throws IOException, FileNotFoundException {
    BufferedReader reader = new BufferedReader(new FileReader(this.collocationRawData));
    String line = reader.readLine();
    StringBuffer result = new StringBuffer("[");
    int counter = 20;
    while (line != null && counter > 0) {
      if (line.startsWith("Key")) {
        if (result.length() > 1) result.append(", ");
        // Key: http bit.ly: Value: 49952.000139875745 <- format of each line
        String[] split = line.split(":");
        result.append("{\"tag\": \"").append(split[1].trim()).append("\", \"count\": \"")
            .append(split[3].trim()).append("\"}");
      }
      line = reader.readLine();
      counter--;
    }
    result.append("]");
    responseWriter.write(result.toString());
  }

  @RequestMapping(value="/data/colloc/bottom.data", method = RequestMethod.GET)
  public void bottomValues(final Model model, final Writer responseWriter) throws IOException, FileNotFoundException {
        BufferedReader reader = new BufferedReader(new FileReader(this.collocationRawData));
    String line = reader.readLine();

    LinkedList<String> entries = new LinkedList<String>();
    while (line != null) {
      if (line.startsWith("Key")) {
        // Key: http bit.ly: Value: 49952.000139875745 <- format of each line
        String[] split = line.split(":");
        StringBuffer buffer = new StringBuffer();
        buffer.append("{\"tag\": \"").append(split[1].trim()).append("\", \"count\": \"")
            .append(split[3].trim()).append("\"}");
        entries.addLast(buffer.toString());
        if (entries.size() > 20)
          entries.removeFirst();
      }
      line = reader.readLine();
    }

    StringBuffer result = new StringBuffer("[");
    for (String entry : entries) {
      if (result.length() > 1) {
        result.append(", ");
      }
      result.append(entry);
    }
    result.append("]");
    responseWriter.write(result.toString());
  }

  @RequestMapping(value="/data/colloc/chart.data", method = RequestMethod.GET)
  public void chart(final Model model, final Writer responseWriter) throws IOException, FileNotFoundException {
    BufferedReader reader = new BufferedReader(new FileReader(this.collocationRawData));
    String line = reader.readLine();
    StringBuffer result = new StringBuffer("[[");
    int counter = 0;
    while (line != null) {
      if (line.startsWith("Key")) {
        if (counter % 1000 == 0) {
          if (result.length() > 2) result.append(",");
          // Key: http bit.ly: Value: 49952.000139875745 <- format of each line
          // [2, 7792.4952347008675] <- format of the target lines
          String[] split = line.split(":");
          String member = split[3].trim();
          int index = member.indexOf('.');
          String y = member.substring(0, index);
          result.append("[").append(counter).append(", ")
              .append(y).append("]");
        }
      }
      line = reader.readLine();
      counter++;
    }
    result.append("]]");
    responseWriter.write(result.toString());
  }

}
